package com.string;

import java.util.Arrays;

public class StringControl {
	
	
	public static String subString(String s,int start,int end){
		if(end<start){
			throw new ArrayIndexOutOfBoundsException("结束下标不能小于开始下标");
		}
		if(end>s.length()){
			throw new ArrayIndexOutOfBoundsException("结束位置大于字符串长度");
		}
		if(start<0){
			throw new ArrayIndexOutOfBoundsException("开始位置必须为大于等于0的值");
		}
		
		int length = end - start;
		char[] cs = new char[length];
		for (int i = start,j = 0; i < end; i++,j++) {
			cs[j] = s.charAt(i);
		}
		return new String(cs);
	}
	
	// 查询存在位置
	public static int indexOf(String s,String in,int start){
		if(start < 0){
			throw new ArrayIndexOutOfBoundsException("开始位置必须为大于等于0的值");
		}
		int s_index = start;
		int in_index = 0;
		int in_length= in.length();
		for (; s_index < s.length()&&in_index<in_length; s_index++) {
			if(s.charAt(s_index) == in.charAt(in_index)){
				in_index++;
			}else{
				in_index=0;
			}
		}
		if(in_index == in_length){
			return s_index - in_index;
		}else{
			return -1;
		}
	}
	
	public static String[] split(String s,String split){
		
		if(split==null){
			throw new NullPointerException("分隔符不能为null");
		}
		if(split.isEmpty()){
			String[] split_s = new String[s.length()];
			for (int i = 0; i < split_s.length; i++) {
				split_s[i] = String.valueOf(s.charAt(i));
			}
			return split_s;
		}
		
		int split_length = s.length()/(split.length()+1)+1;// 计算分配数组最大大小
		String[] split_s = new String[split_length];
		int writeIndex = 0;
		int s_index = 0;
		
		while(s_index<s.length()){
			int index = indexOf(s, split, s_index);
			if(index == -1){
				split_s[writeIndex++] = subString(s, s_index, s.length());
				break;
			}
			String split_string = subString(s, s_index, index);
			if(!split_string.isEmpty()){
				split_s[writeIndex++] = split_string;
			}
			s_index = index+split.length();
		}
		
		if(writeIndex != split_length){
			String[] oldsplit_s = split_s;
			split_s = new String[writeIndex];
			System.arraycopy(oldsplit_s, 0, split_s, 0, writeIndex);
		}
		return split_s;
	}
	
	// 连接字符串
	public static String getString(Object...objs){
		String ss[] = new String[objs.length];
		int length = 0;
		for (int i = 0; i < ss.length; i++) {
			ss[i] = String.valueOf(objs[i]);
			length+=ss[i].length();
		}
		char cs[] = new char[length];
		int writeIndex = 0;
		for (int i = 0; i < ss.length; i++) {
			String s = ss[i];
			System.arraycopy(s.toCharArray(), 0, cs, writeIndex, s.length());
			writeIndex += s.length();
		}
		
		return new String(cs);
	}
	public static void main(String[] args) {
		System.out.println(subString("12345", 2, 5));
		System.out.println(indexOf("1234567890", "90", 5));
		System.out.println(Arrays.toString(split("abababababababababaabbaba", "b")));
		System.out.println(getString(1,2,3,5,"---"));  // 输出 1235---
	}
}
